package com.way2sms.way2inbox;

/*
*
*  Project : Way2Inbox
*  Started Date: 12-12-2014
*  Developer : P Srinivas Varma
*  Build for All Android Devices above API 9.
*  Company Build by Way2online Services pvt ltd.
*
* */

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.UUID;

import www.way2inbox.adapter.SimsListAdapter;
import www.way2inbox.comm.Errorcode;
import www.way2inbox.comm.ReadWebpageAsyncTask;
import www.way2inbox.comm.SessionManager;
import www.way2inbox.comm.TaskListener;
import www.way2inbox.comm.TelephonyInfo;
import www.way2inbox.common.Constants;
import www.way2inbox.common.IsOnline;
import www.way2inbox.common.PrintMsg;
import www.way2inbox.common.Urls;
import www.way2inbox.data.simsfetch;

public class Startup extends Activity implements TaskListener,AdapterView.OnItemClickListener{

    SharedPreferences UserCredentials;
    SharedPreferences.Editor UserCredentialsEditors;
    Boolean UserRegistered;


    // Variable of Registration of User;
    RelativeLayout StartupOverlay,RegisterOverlay,AutoVerification;
    FrameLayout CapchaLayout;
    EditText PhoneNumber,VerifCode,CaptCode;
    TextView ProcessStatus,MobileStatus;
    ProgressBar progressbar;
    Button Login,Capt_OK,Capt_Cancel;
    JSONObject register;
    String MobileNumber,vcode;
    String Username,Gender,PlayStoreID,DOB,MID,EmailID,ExtraID,Phone1=null,Phone2=null,Capt_URL;
    Urls urls;
int times=0;
    Boolean Regist=false;


    Spinner spinnerOsversions;
    TextView selVersion;
    private String[] state = { "Mobile Number", "Donut", "Eclair", "Froyo",
            "Gingerbread", "HoneyComb", "IceCream Sandwich", "Jellybean",
            "kitkat" };
    ListView MultiSims;
    SimsListAdapter SimsAdapter;


    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

        /*
        * Getting details from Shared Preference,
        * so if User is first time for the app then
        * This Activity will be shown or else
        * Activity will be directed to Messages Activity..
        *
        * */


        UserCredentials = getApplicationContext().getSharedPreferences(getResources().getString(R.string.USRD), 0);

        UserRegistered=UserCredentials.getBoolean(getResources().getString(R.string.REG),false);
        if(!UserRegistered) {

        /*
        *   User is Using this application for the first time so he need to register to use the application.
        *
        * */
            session = new SessionManager(getApplicationContext());
            // Checking user session
            System.out.println("Going to check session");
            if (!session.isLoggedIn()) {
                requestWindowFeature(Window.FEATURE_NO_TITLE);
                setContentView(R.layout.activity_startup);

            /*
            * Coding for the registration of the user.
            * */
                AutoVerification= (RelativeLayout) findViewById(R.id.AutoVerification);
                RegisterOverlay= (RelativeLayout) findViewById(R.id.RegisterOverlay);

                StartupOverlay = (RelativeLayout) findViewById(R.id.StartupOverlay);
                CapchaLayout = (FrameLayout) findViewById(R.id.CapchaLayout);
                Capt_OK = (Button) findViewById(R.id.Capt_OK);
                Capt_Cancel = (Button) findViewById(R.id.Capt_Cancel);
                PhoneNumber = (EditText) findViewById(R.id.Phonenumber);
                VerifCode = (EditText) findViewById(R.id.VerifCode);
                MobileStatus = (TextView) findViewById(R.id.NumberStatus);
                MobileStatus.setText("");

            /*
            * Getting Play Store Email id,UserName,Gender,DOB,MID :
            * */

                //Play Store ID
                PlayStoreID = getEmail(getApplicationContext());

                //MID Device ID...
                try {
                    TelephonyManager phonespecs = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    MID = phonespecs.getDeviceId();
                    String macAddr = "", androidId = "";
                    if (MID == null) {
                        WifiManager wifiMan = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
                        WifiInfo wifiInf = wifiMan.getConnectionInfo();
                        macAddr = wifiInf.getMacAddress();
                        androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
                        UUID deviceUuid = new UUID(androidId.hashCode(), macAddr.hashCode());
                        MID = deviceUuid.toString();

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

//            urls =new Urls();
//            Capt_URL= urls.captchaurl+"?un=randomstring";
//            imageView = (ImageView)findViewById(R.id.CapchaURL);
//
//            if(!IsOnline.getConnection(Startup.this)){
//                PrintMsg.SetToast(Startup.this, getResources().getString(R.string.NoInternet), 1);
//                return;
//            }
//
//            // Create an object for subclass of AsyncTask
//            GetXMLTask task = new GetXMLTask();
//            // Execute the task
//            task.execute(new String[] { Capt_URL });


                //Remaining Details...
                OwnerInfo oi = new OwnerInfo(Startup.this);
                Username = oi.name;
                Gender = null;
                EmailID = oi.email;

                DOB = null;
                ExtraID = oi.accountName;
                if(EmailID ==null && ExtraID !=null){
                    EmailID=ExtraID;
                }


                ArrayList<simsfetch> AllSIMS = getALLSIMS();
                MultiSims = (ListView) findViewById(R.id.MulitpleNumbers);
                SimsAdapter = new SimsListAdapter(Startup.this, R.layout.adapter_multiple_numbers, AllSIMS);
                MultiSims.setAdapter(SimsAdapter);
                MultiSims.setOnItemClickListener(this);
                PrintMsg.setLogerror(getApplicationContext(),"-------->"+AllSIMS.size());
                if (AllSIMS.size() == 0) {
                    MultiSims.setVisibility(View.GONE);
                    PhoneNumber.setVisibility(View.VISIBLE);
                }
                if (AllSIMS.size() == 1) {
                    MobileStatus.setText("Please select to confirm.");


                } else {
                    MobileStatus.setText("Please select to your nummber.");
                }


//            spinnerOsversions = (Spinner) findViewById(R.id.osversions);
//            ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
//                    android.R.layout.simple_spinner_item, state);
//            adapter_state.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//            spinnerOsversions.setAdapter(adapter_state);
//            spinnerOsversions.setOnItemSelectedListener(this);

                //THIS IS FOR THE AUTO VERIFICATION CODE PROCESS..
                VerificaitonStatus  =(TextView)findViewById(R.id.VerificaitonStatus);
                UserVerifCode       =(TextView)findViewById(R.id.UserVerifCode);
                VerifProcessUpdate  =(TextView)findViewById(R.id.VerifProcessUpdate);

                ProcessStatus = (TextView) findViewById(R.id.intro_progress_status);
                progressbar = (ProgressBar) findViewById(R.id.intro_progressbar);
                CaptCode = (EditText) findViewById(R.id.RegCapcha);

                VerifCode.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        vcode = VerifCode.getText().toString();
                        if (vcode.length() == 6) {
//                            hideKeyboard();

                            RequestServer(0);
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });


                PhoneNumber.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

//                    PrintMsg.setLogerror(Startup.this,"beforeTextChanged>>>"+s+"  >>>"+count);

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {


                        MobileNumber = PhoneNumber.getText().toString();

//                    PrintMsg.setLogerror(Startup.this,"onTextChanged>>>" + s + "  >>>" + MobileNumber.length());
                        //WHEN USER TYPES FOR VERIFICATION CODE


                        // when user types 10 number of mobile .
                        if (MobileNumber.length() == 10) {
//                        PhoneNumber.setFocusable(false);

                            //Checking weather number is a valid number or not
                            if (MobileNumber.substring(0, 1).matches(Constants.Validno)) {

                                if (times == 0 && Phone1 == null) {
                                    Phone1 = MobileNumber;
                                    times = 1;
                                    PhoneNumber.setText("");
                                    MobileStatus.setText("Confirm mobile number");
                                } else {
                                    Phone2 = MobileNumber;
                                    if (Phone1.equalsIgnoreCase(Phone2)) {
//                                        hideKeyboard();
                                        MobileStatus.setText(Phone2);

                                        RequestServer(0);;

//                                    PrintMsg.SetToast(Startup.this, "Requesting Server", 1);
//                                    UserCredentialsEditors=UserCredentials.edit();
//                                    UserCredentialsEditors.putBoolean(getResources().getString(R.string.REG),true);
//                                    UserCredentialsEditors.commit();
                                    } else {
//                                    PrintMsg.SetToast(Startup.this, getResources().getString(R.string.NomatchNO), 1);
                                        MobileStatus.setText(getResources().getString(R.string.NomatchNO));
                                        times = 0;
                                        PhoneNumber.setText("");
                                    }
                                }

                            } else {

                                //Wrong number entered so push a status message
                                PrintMsg.SetToast(Startup.this, getResources().getString(R.string.NovalidNumber), 1);
                            }

                        }


                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });


                Capt_OK.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (CaptCode.length() == 6) {
                            RequestServer(1);
                        }
                        CapchaLayout.setVisibility(View.GONE);
                    }
                });
                Capt_Cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CapchaLayout.setVisibility(View.GONE);
                    }
                });


            /*
            * End of Registration ..
            * */

            }else{
                Intent Messages = new Intent(Startup.this, Messages.class);
                startActivity(Messages);
                finish();
            }
            } else {

            /*
            * User is already Registered so Redirecting to Messages Activity..
            * */


            }




	}

    private ArrayList<simsfetch> getALLSIMS() {
        ArrayList<simsfetch> res=new ArrayList<>();

        TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        simsfetch obj;
        if(tm.getLine1Number()!=null && tm.getLine1Number().length()>9){
            PrintMsg.setLogerror(Startup.this,"SIMS DETAILS :"+tm.getLine1Number()+"\n"+tm.getDeviceId()+"\n"+tm.getSimState()+"\n"+tm.getPhoneType());
           obj = new simsfetch(tm.getLine1Number(),tm.getSimSerialNumber(),tm.getDeviceId());
            res.add(obj);

        }



        return res;
    }
int again=0;
    String repNumber;
    public void onItemClick(AdapterView<?> parent, View view, int position,
                               long id) {
        MultiSims.setSelection(position);
        TextView selState=(TextView) view.findViewById(R.id.sim_no);

//        PrintMsg.SetToast(Startup.this,"You Selected :"+selState.getText().toString(),1);

        if(again==0){
            repNumber=selState.getText().toString();
            PrintMsg.SetToast(Startup.this,"Press again to confirm",1);
            again=1;
            return;
        }
        if(again==1 && repNumber.equalsIgnoreCase(selState.getText().toString())){


            try {
                repNumber = repNumber.replaceAll(" ", "");
                repNumber = repNumber.substring(repNumber.length() - 10,repNumber.length());
                if(repNumber.substring(0, 1).matches(Constants.Validno)) {
                    MobileStatus.setText(repNumber);
                    RequestServer(0);
                }else{
                    //Wrong number entered so push a status message
                    PrintMsg.SetToast(Startup.this, getResources().getString(R.string.NovalidNumber), 1);
                    return;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            MultiSims.setVisibility(View.GONE);
//            again=0;

            //Writing code to Hide remaining Numbers



        }else{
            repNumber=selState.getText().toString();
            PrintMsg.SetToast(Startup.this,"Press again to confirm",1);
            again=1;
            return;
        }
    }

//   d

    ProgressBar Progress;
    public void RequestServer(int captcha){
        if(!IsOnline.getConnection(Startup.this)){
            PrintMsg.SetToast(Startup.this, getResources().getString(R.string.NoInternet), 1);
            return;
        }
        urls=new Urls();
        if(PhoneNumber.getVisibility()!=View.GONE){

            PhoneNumber.setVisibility(View.GONE);
        }
        register = new JSONObject();
        Progress=(ProgressBar)findViewById(R.id.intro_progressbar);
        ReadWebpageAsyncTask readAsyncTask=new ReadWebpageAsyncTask(Startup.this);
        PrintMsg.SetToast(Startup.this,"Confirmed  final"+MobileStatus.getText().toString(),0);
        try {
        if(!VerifTime) {

                register.put("G", Gender);
                register.put("UN", Username);
                register.put("MNO", MobileStatus.getText().toString());
                register.put("EID", EmailID);
                register.put("DOB", DOB);
                //                                register.put("CCD", CaptCode.getText().toString());
                register.put("MID", MID);

                if (captcha == 1) {
                    register.put("CCD", CaptCode.getText().toString());
                    shp = getSharedPreferences("forgotpass", 0);
                    editor = shp.edit();
                    String cookie = shp.getString("cook", null);
                    register.put("Cookie", cookie);
                }

        }else{
            register.put("MNO", MobileStatus.getText().toString());
            register.put("VCD", VerifCode.getText().toString());
            register.put("EID", EmailID);
            register.put("MID", MID);
            if (captcha == 1) {
                register.put("CCD", CaptCode.getText().toString());
                shp = getSharedPreferences("forgotpass", 0);
                editor = shp.edit();
                String cookie = shp.getString("cook", null);
                register.put("Cookie", cookie);
            }
        }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(!IsOnline.getConnection(Startup.this)){
            PrintMsg.SetToast(Startup.this, getResources().getString(R.string.NoInternet), 1);
return;
        }else{
            if(!VerifTime) {
                Regist = true;
                readAsyncTask.execute(register, urls.Loginurl);
            }else{
                readAsyncTask.execute(register, urls.MobileVerification);
            }
        }
        //finally registered then stored..

    }

    public void SendStatus(String Msg){
        ProcessStatus.setVisibility(View.VISIBLE);
        ProcessStatus.setText(Msg);
//        PhoneNumber.setFocusable(true);
    }
    private ProgressDialog progressDialog;
    @Override
    public void onTaskStarted() {
//        progressDialog = ProgressDialog.show(Startup.this, "Loading", "Please wait a moment!");
        Progress.setVisibility(View.VISIBLE);
    }

    Boolean VerifTime=false;
    @Override
    public void onTaskFinished(String result) {
        Errorcode ec= new Errorcode();

        if (Progress != null) {
            Progress.setVisibility(View.GONE);
            if(result.toString()==null || result.toString().equalsIgnoreCase("error") ){
                PrintMsg.SetToast(Startup.this, getResources().getString(R.string.NetError), 1);
            }
        }
        JSONObject jsvn=null;
        try {
            jsvn=new JSONObject(result.toString());
            PrintMsg.setLogerror(Startup.this,jsvn.toString());
            if(jsvn.get("CD").toString().equals("05")){
//                VerifCode.setVisibility(View.VISIBLE);
                VerifTime=true;
//                PhoneNumber.setVisibility(View.GONE);

                RegisterOverlay.setVisibility(View.GONE);
                AutoVerification.setVisibility(View.VISIBLE);

                if(MultiSims.getVisibility()!=View.GONE){
                    MultiSims.setVisibility(View.GONE);
                }

                AuthenicationScreen();





            }else if(jsvn.get("CD").toString().equals("09")){
                if(jsvn.has("TK")) {
                    session = new SessionManager(getApplicationContext());
                    // MobileNO = (EditText)findViewById(R.id.UserName);
                    session.createLoginSession(jsvn.get("TK") + "", " ", MobileStatus.getText().toString());
                    //System.out.println("sdxccccccccccccc   "+result.trim().equals("USER_NAME"));


                    Intent i = new Intent(Startup.this, Messages.class);
                    finish();
                    Startup.this.startActivity(i);
                }
            }else {

                PrintMsg.SetToast(Startup.this, ec.SignUp(jsvn.getString("CD")), 1);

            }


            //TO MANY REQUEST FOR SERVER SO HERE CAPTCODE HAS TO ENTERED BY USER , SO LAYOUT IS SET VISIBLE NOW
            if(jsvn.get("CD").toString().equals("03")){
                urls =new Urls();
                Capt_URL= urls.captchaurl+"?un=randomstring";
                imageView = (ImageView)findViewById(R.id.CapchaURL);

                if(!IsOnline.getConnection(Startup.this)){
                    PrintMsg.SetToast(Startup.this, getResources().getString(R.string.NoInternet), 1);
                    return;
                }

                // Create an object for subclass of AsyncTask
                GetXMLTask task = new GetXMLTask();
                // Execute the task
                task.execute(new String[] { Capt_URL });
                CapchaLayout.setVisibility(View.VISIBLE);


            }


        } catch(JSONException e){
            e.printStackTrace();
        }

    }





        public  String getEmail(Context context) {
            AccountManager accountManager = AccountManager.get(context);
            Account account = getAccount(accountManager);

            if (account == null) {
                return null;
            } else {
                return account.name;
            }
        }

        private  Account getAccount(AccountManager accountManager) {
            Account[] accounts = accountManager.getAccountsByType("com.google");
            Account account;
            if (accounts.length > 0) {
                account = accounts[0];
            } else {
                account = null;
            }
            return account;
        }

//    public void hideKeyboard(){
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
//    }

    public class OwnerInfo {
        // this class allows to get device information. It's done in two steps:
        // 1) get synchronization account email
        // 2) get contact data, associated with this email
        // by https://github.com/jehy


        //WARNING! You need to have permissions
        //
        //<uses-permission android:name="android.permission.READ_CONTACTS" />
        //<uses-permission android:name="android.permission.GET_ACCOUNTS" />
        //
        // in your AndroidManifest.xml for this code.

        public String id = null;
        public String email = null;
        public String phone = null;
        public String accountName = null;
        public String name = null;

        public OwnerInfo(Activity MainActivity) {
            try {
                final AccountManager manager = AccountManager.get(MainActivity);
                final Account[] accounts = manager.getAccountsByType("com.google");
                if (accounts[0].name != null) {
                    accountName = accounts[0].name;
                    String where = ContactsContract.CommonDataKinds.Email.DATA + " = ?";
                    ArrayList<String> what = new ArrayList<String>();
                    what.add(accountName);
                    Log.e("Got account", "Account " + accountName);
                    for (int i = 1; i < accounts.length; i++) {
                        where += " or " + ContactsContract.CommonDataKinds.Email.DATA + " = ?";
                        what.add(accounts[i].name);
                        Log.e("Got account", "Account " + accounts[i].name);
                    }
                    String[] whatarr = (String[]) what.toArray(new String[what.size()]);
                    ContentResolver cr = MainActivity.getContentResolver();
                    Cursor emailCur = cr.query(
                            ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                            where,
                            whatarr, null);
                    if (emailCur.moveToNext()) {
                        id = emailCur
                                .getString(emailCur
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID));
                        email = emailCur
                                .getString(emailCur
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                        String newName = emailCur
                                .getString(emailCur
                                        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        if (name == null || newName.length() > name.length())
                            name = newName;

                        Log.e("Got contacts", "ID " + id + " Email : " + email
                                + " Name : " + name);
                    }

                    emailCur.close();
                    if (id != null) {

                        // get the phone number
                        Cursor pCur = cr.query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                        + " = ?", new String[]{id}, null);
                        while (pCur.moveToNext()) {
                            phone = pCur
                                    .getString(pCur
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            Log.e("Got contacts", "phone" + phone);
                        }
                        pCur.close();
                    }
                }

            }catch (ArrayIndexOutOfBoundsException e){
PrintMsg.SetToast(Startup.this,getResources().getString(R.string.NoSupport),0);
            }
        }
    }
//    @Override
//    public boolean onTouch(View v, MotionEvent event) {
//        // TODO Auto-generated method stub
//        InputMethodManager imm = (InputMethodManager)getSystemService(Context.
//                INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
//        return true;
//    }



    long curWaitTime;
    boolean reload;
    ImageView imageView;
    //    WebView webview;
    SessionManager session;
    //SessionSignup signupsession;
    SharedPreferences shp;
    //String cookie;
    SharedPreferences.Editor editor;
    //Captcha class below
    private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
        private ProgressDialog dialog;
        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(Startup.this, "",
                    "Loading... Please wait...", true);
            dialog.setMax(100);
        }
        @Override
        protected Bitmap doInBackground(String... urls) {
            reload =false;
            long waitTime = 4000;// or whatever you want the timeout length to be long
            curWaitTime = 0;
            Bitmap map = null;
            while (!reload && curWaitTime < waitTime)
            {
                try {
                    for (String url : urls) {
                        map = downloadImage(url);
                    }
                }

                catch (Exception e) {
                    e.printStackTrace();
                }
            	 /*if(map!=null){
            		 curWaitTime=waitTime;
            		 reload =true;
                 }else{
                	 curWaitTime =curWaitTime+ 100;
                 }*/
                curWaitTime =curWaitTime+ 100;
            }
            return map;
        }

        // Sets the Bitmap returned by doInBackground
        @Override
        protected void onPostExecute(Bitmap result) {

            if (dialog != null) {
                dialog.dismiss();
                dialog = null;
                if(result!=null){
                    imageView.setImageBitmap(result);}
                else{
                   PrintMsg.SetToast(Startup.this,getResources().getString(R.string.NetError),1);
                }
            }

        }


        // Creates Bitmap from InputStream and returns it
        private Bitmap downloadImage(String url) {
            Bitmap bitmap = null;
            InputStream stream = null;
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            bmOptions.inSampleSize = 1;

            try {
                stream = getHttpConnection(url);
                bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
                stream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return bitmap;
        }

        // Makes HttpURLConnection and returns InputStream
        private InputStream getHttpConnection(String urlString)throws IOException {
            InputStream stream = null;
            URL url = new URL(urlString);

            URLConnection connection = url.openConnection();

            try {

                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();
                String cookie = httpConnection.getHeaderField("Set-Cookie");
                shp=getSharedPreferences("forgotpass", 0);

                editor = shp.edit();
                editor.putBoolean("cook1", true);
                if(cookie!=null){
                    editor.putString("cook",cookie);
                    editor.commit();
                }
                String[] cookies1 = cookie.split(";");
                if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    stream = httpConnection.getInputStream();
                    reload =true;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return stream;
        }
    }




    TextView VerificaitonStatus,UserVerifCode,VerifProcessUpdate;
    private BroadcastReceiver mIntentReceiver;
    @Override
    protected void onResume() {
        super.onResume();

        IntentFilter intentFilter = new IntentFilter("SmsMessage.intent.MAIN");
        mIntentReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String msg = intent.getStringExtra("get_msg");
                msg = msg.replace("\n", "");

                Log.i("BroadcastReceiver","onResume ++>>>>>>1 "+msg);

                new CountDownTimer(2000, 1000) {

                    public void onTick(long millisUntilFinished) {

                            	VerifProcessUpdate.setText(""+millisUntilFinished
                                                / 1000);
//                            	Auth_title.setText("Authenicating with Server");
                    }

                    public void onFinish() {
                          RegisterOverlay.setVisibility(View.VISIBLE);
                        AutoVerification.setVisibility(View.GONE);
                    }
                }.start();

                UserVerifCode.setText(msg);
                VerifCode.setText(msg);;

                AutoVerification.setVisibility(View.VISIBLE);
                // success123


            }
        };
        this.registerReceiver(mIntentReceiver, intentFilter);
    }

    @Override
    protected void onPause() {

        super.onPause();
        this.unregisterReceiver(this.mIntentReceiver);
    }

    private void AuthenicationScreen() {
        // TODO Auto-generated method stub

//        RegisterOverlay.setVisibility(View.VISIBLE);
//        AutoVerification.setVisibility(View.GONE);
        // triggering for hidding the keyboard when touching the screen..

        AutoVerification.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });


        new CountDownTimer(40000, 1000) {

            public void onTick(long millisUntilFinished) {

            VerifProcessUpdate.setText(""+millisUntilFinished
                / 1000);
            }

            public void onFinish() {
//            	Auth_time.setText("Time Over");
                AutoVerification.setVisibility(View.GONE);
                RegisterOverlay.setVisibility(View.VISIBLE);
                VerifCode.setVisibility(View.VISIBLE);
            }
        }.start();
    }
}

